package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模板")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        log.debug("UserRegDTO="+userRegDTO);

        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        log.debug("UserVO="+userVO);
        if(userVO != null){//用户名被占用
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        //未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        log.debug("User:"+user);
        userMapper.insertUser(user);

        return JsonResult.ok();
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        log.debug("UserLoginVO="+ userLoginDTO);

        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }

        String password = userLoginDTO.getPassword();
        if(userVO.getPassword().equals(password)){
            session.setAttribute("user",userVO);
            return JsonResult.ok();
        }

        return new JsonResult((StatusCode.PASSWORD_ERROR));
    }

    @ApiOperation(value = "查看登入状态")
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");

        return JsonResult.ok(userVO);
    }


    @ApiOperation(value = "登出功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }


}
